package org.finesys.monitor.notifier;

import cn.hutool.core.date.DateUtil;
import de.codecentric.boot.admin.server.domain.entities.Instance;
import de.codecentric.boot.admin.server.domain.entities.InstanceRepository;
import de.codecentric.boot.admin.server.domain.events.InstanceEvent;
import de.codecentric.boot.admin.server.domain.events.InstanceStatusChangedEvent;
import de.codecentric.boot.admin.server.notify.AbstractStatusChangeNotifier;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.Date;
import java.util.Map;

import static de.codecentric.boot.admin.server.domain.values.StatusInfo.*;

/**
 * 自定义服务通知
 */
@Component
@Slf4j
public class CustomNotifier extends AbstractStatusChangeNotifier {
    public CustomNotifier(InstanceRepository repository) {
        super(repository);
    }

    @Override
    protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
        //服务名
        String serviceName = instance.getRegistration().getName();
        //服务地址
        String serviceUrl = instance.getRegistration().getServiceUrl();
        //服务状态
        String serviceStatus = instance.getStatusInfo().getStatus();
        //详情
        Map<String, Object> details = instance.getStatusInfo().getDetails();
        //当前服务掉线时间
        String date = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
        //拼接信息内容
        StringBuilder sb = new StringBuilder();
        sb.append("服务名:【").append(serviceName).append("】");
        sb.append("服务状态:【").append(serviceStatus).append("】");
        sb.append("服务地址:【").append(serviceUrl).append("】");
        sb.append("时间:【").append(date).append("】");
        //处理结果
        return Mono.fromRunnable(() -> {
            //只处理变动的事件
            if (event instanceof InstanceStatusChangedEvent) {
                switch (serviceStatus) {
                    case STATUS_DOWN:
                        if (log.isInfoEnabled()) {
                            log.info("健康检查未通过，{}", sb);
                        }
                        break;
                    case STATUS_OFFLINE:
                        if (log.isInfoEnabled()) {
                            log.info("服务离线，{}", sb);
                        }
                        break;
                    case STATUS_UP:
                        if (log.isInfoEnabled()) {
                            log.info("服务上线，{}", sb);
                        }
                        break;
                    case STATUS_UNKNOWN:
                        if (log.isInfoEnabled()) {
                            log.info("服务未知异常，{}", sb);
                        }
                        break;
                    default:
                        if (log.isInfoEnabled()) {
                            log.info("{}", sb);
                        }
                        break;
                }
            }
        });
    }
}
